package studyguide.ch12;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class Person {

	private String name;
	
	private int age;

	public Person() {
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Person(byte [] data) {
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(data);
			DataInputStream dis = new DataInputStream(bais);
			name = dis.readUTF();
			age = dis.readInt();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	public byte[] serialize() {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);
			dos.writeUTF(name);
			dos.writeInt(age);
			return baos.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(name);
		buffer.append(": ");
		buffer.append(age);
		return buffer.toString();
	}

	/* Getters and setters: */
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
}
